<?php

class projectModel extends Model{
    public function getListTree() {
        $list = $this->order('sort asc')->getAll('is_delete=?', 0);
        return $this->getTree($list);
    }

    public function getListTreeAll() {
        $list = $this->order('sort asc')->getAll('is_delete=?', 0);
        return $this->fullTree($list);
    }

    public function fullTree($data, $parentId = 0) {
        if (!$data || !is_array($data)) {
            return [];
        }
        $childArray = $this->_getChildren($data, $parentId);
        if (!$childArray) {
            return array();
        }

        $treeArray = array();
        foreach ($childArray as $lines) {
            $treeArray[$lines['id']] = array(
                'category_id' => intval($lines['id']),
                'name' => $lines['name'],
                'image' => $lines['images'],
                'add_time' => $lines['add_time'],
                'sort' => $lines['sort'],
                'categral' => $lines['categral'],
                'update_time' => $lines['update'],
                //  'type' => $lines['type'],
                'child' => $this->fullTree($data, $lines['id']),
            );
        }

        return array_values($treeArray);
    }
    public function getTree($data, $parentId = 0) {
        if (!$data || !is_array($data)) {
            return [];
        }
        $childArray = $this->_getChildren($data, $parentId);
        if (!$childArray) {
            return array();
        }

        $treeArray = array();
        foreach ($childArray as $lines) {
            $treeArray[$lines['id']] = array(
                'id' => intval($lines['id']),
                'name' => $lines['name'],
                'images' => $lines['image'],
                'categral' => $lines['categral'],
                'child' => $this->getTree($data, $lines['id']),
            );
        }

        return array_values($treeArray);
    }

    /**
     * 无限级分类树-获取子类
     *
     * @access public
     *
     * @param array $data 树的数组
     * @param integer $id 父类ID
     *
     * @return array
     */
    protected function _getChildren($data, $id) {

        $childrenArray = array();
        foreach ($data as $value) {
            if ($value['parent_id'] == $id) {
                $childrenArray[] = $value;
            }
        }

        return $childrenArray;
    }
}